package com.ly.mpayment.rest.up.honglu;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.Config;
import com.ly.mpayment.core.util.DateUtils;
import com.ly.mpayment.core.util.HttpClient;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import java.util.HashSet;
import java.util.Set;

@Component
@Path("honglu")
public class HongLuRest {

    Logger logger = Logger.getLogger(HongLuRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;


    @SuppressWarnings("static-access")
    @Path("callBack")
    @POST
    public String callBack(String data) {
        logger.info("honglu_callback:" + data);
        if (!StringUtils.isBlank(data)) {
            JSONObject jsonD = JSONObject.parseObject(data);
            UpOrder order = upOrderService.findById(jsonD.getString("ordernum"));
            if (order != null && jsonD.getString("state").equals("2") && order.getStatus() == Config.status[0]) {
                order.setRemark(jsonD.containsKey("serialno") ? jsonD.getString("serialno") : jsonD.getString("desc") );
                RechargeRest.successUpOrder.add(order);
                jsonD.clear();
                jsonD.put("code","0000");
                jsonD.put("desc","");
                return jsonD.toString();
            } else if (order != null && order.getStatus() == Config.status[0] && jsonD.getString("state").equals("3")) {
                order.setRemark(jsonD.getString("desc"));
                RechargeRest.failtUpOrder.add(order);
                jsonD.clear();
                jsonD.put("code","0000");
                jsonD.put("desc","");
                return jsonD.toString();
            } else {
                logger.info("honglu_not_found_order:" + jsonD.getString("ordernum") + "," );
            }
        }
        return "0";
    }


    /**
     * 订单提交
     * @param order
     * @param shop
     */
    public void commitOrder(UpOrder order, UpShopInfo shop) {

        String ts = new DateUtils().toTimeStamp();
        JSONObject data = new JSONObject();
        data.put("userid", shop.getAppId());
        data.put("orderid", order.getUporderuuid());
        data.put("echo", order.getUporderuuid());
        data.put("timestamp", ts);
        data.put("version", "1.0");
        data.put("mobile",order.getUpphonenum());
        data.put("packcode", order.getUpShopPro().getProductCode());
        data.put("flowtype", "1001");
        data.put("callback_url", shop.getOrderCallAddress());
        data.put("chargeSign", MD5.md5(shop.getAppId()+order.getUporderuuid()+shop.getUpkey()+
                order.getUporderuuid()+ts));
        String result = HttpClient.post(shop.getOrderCommitAddress(), data.toString());
        logger.info("commitOrder_honglu:"+result+","+data.toString());
        if (!StringUtils.isBlank(result)) {
            JSONObject json = JSONObject.parseObject(result);
            if (json.containsKey("code") && json.getString("code").equals("0000")) {
                this.upOrderService.updateUpOrderMsg(order,"",json.getString("desc"));
            } else if(json.containsKey("code") && errorCode.contains(json.getString("code"))) {
                order.setRemark(json.getString("desc"));
                RechargeRest.failtUpOrder.add(order);
            }
        } else {
            this.upOrderService.updateUpOrderMsg(order, "","提单失败");
            logger.info("commitOrder_error:" + order.getUpphonenum());
        }
    }

    /**
     * 0001 提交失败，userid为空
     * 0002 提交失败，orderid为空
     * 0003 提交失败，参数错误
     * 0004 提交失败，mobile为空
     * 0005 提交失败，mobile格式错误
     * 0007 提交失败，一小时之内，同一手机号最多提交四次
     * 9999 提交失败，余额不足
     * 0008 提交失败，没有配置产品
     * 0009 提交失败，没有配置有效渠道
     * 0010 订单号已存在(不可失败，需线下核实)
     * 0011 提交失败，未获取基础数据
     * 0012 提交失败，签名验证失败
     * 0030 提交失败，价格不匹配
     */
    Set<String> errorCode = new HashSet<String>(){{
        add("0001");
        add("0002");
        add("0003");
        add("0004");
        add("0005");
        add("0007");
        add("9999");
        add("0008");
        add("0009");
        add("0011");
        add("0012");
        add("0030");
    }};

    /**
     * 订单查询
     * @param upOrder
     * @param shopInfo
     */
    public void queryOrder(UpOrder upOrder, UpShopInfo shopInfo) {
        String ts = new DateUtils().toTimeStamp();
        JSONObject data = new JSONObject();
        data.put("userid", shopInfo.getAppId());
        data.put("orderid", upOrder.getUporderuuid());
        data.put("timestamp", ts);
        data.put("sign", MD5.md5(shopInfo.getAppId()+upOrder.getUporderuuid()+ts+shopInfo.getUpkey()));
        String result =  HttpClient.post(shopInfo.getOrderStatusAddress(), data.toString());
        logger.info("hongluqueryOrder:"+upOrder.getUpphonenum()+":"+result);
        if (!StringUtils.isBlank(result)) {
            JSONObject jsonD = JSONObject.parseObject(result);
            UpOrder order = upOrderService.findById(upOrder.getUporderuuid());
            if (order != null && jsonD.getString("code").equals("0000") && order.getStatus() == Config.status[0]) {
                order.setRemark(jsonD.containsKey("desc") ? jsonD.getString("desc") : "");
                RechargeRest.successUpOrder.add(order);
            } else if (order != null && order.getStatus() == Config.status[0]
                    && jsonD.getString("code").equals("0004")) {
                order.setRemark(jsonD.getString("desc"));
                RechargeRest.failtUpOrder.add(order);
            } else {
                logger.info("honglu_not_found_order:" + jsonD.toString() + ",");
            }
        }
    }

}
